/*
 * Copyright (C) 2008 ProSyst Software GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.modulefusion.featurepack.wicket;

import java.lang.reflect.Field;

import org.apache.wicket.Application;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WicketFilter;
import org.apache.wicket.protocol.http.WicketServlet;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LocalWicketServlet extends WicketServlet {

	final Logger logger = LoggerFactory.getLogger(LocalWicketServlet.class);

	private final WebApplication webApplication;
	private final BundleContext context;

	public LocalWicketServlet(BundleContext context, WebApplication webApplication) {
		this.context = context;
		this.webApplication = webApplication;
		makeOSGiAware();
	}

	@Override
	protected WicketFilter newWicketFilter() {
		return new LocalWicketFilter(webApplication);
	}

	private void makeOSGiAware() {
		try {
			// Hack to be able to set the class loader
			// Wicket expects this always to be done inside the init() method
			Field field = Application.class.getDeclaredField("settingsAccessible");
			field.setAccessible(true);
			Object oldValue = field.get(webApplication);
			field.set(webApplication, true);

			// Adding OSGi class loader hook
			BundleClassLoader bcl = new BundleClassLoader(context);
			webApplication.getApplicationSettings().setClassResolver(bcl);

			field.set(webApplication, oldValue);
		}
		catch (Exception e) {
			logger.error("Error making WebApplication OSGi aware", e);
		}
	}

}
